﻿using System;
using System.Collections.Generic;
using System.Text;

using TRPOP.CMS.Model;
using TRPOP.CMS.DALFactory;
using TRPOP.Common;
using System.Web;
using System.IO;
using System.Data;

namespace TRPOP.CMS.Business
{
    public class ContentUpFileManage
    {

        private IContentUpFileDAL Idal;
        public ContentUpFileManage()
        {
            Idal = DataAccess.CreateContentUpFileDAL();
        }

        #region 保存 Save
        ///	<summary>
        ///	保存
        ///	</summary>
        ///	<param name="ContentUpFileInfo"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult Save(ContentUpFileInfo info)
        {
            if (info.NodeID > 0)
            {
                SerializableDictionary<string, string> oDic = new NodeManage().GetNodeURLForSourcePSN();
                if (!oDic.ContainsKey(info.NodeID.ToString() + "_PSNSourceRoot"))
                {
                    NodeManage oNodeManage = new NodeManage();
                    oDic = oNodeManage.SaveNodeURLForSourcePSN(oNodeManage.GetInfoById(info.NodeID));
                }
                if (oDic.ContainsKey(info.NodeID.ToString() + "_PSNSourceRoot") && oDic.ContainsKey(info.NodeID.ToString() + "_PSNSourceRootURL"))
                {
                    info.FileURL = info.FileRoot.Replace(oDic[info.NodeID.ToString() + "_PSNSourceRoot"], oDic[info.NodeID.ToString() + "_PSNSourceRootURL"]);
                }
            }
            return Idal.Save(info);
        }

        #endregion

        #region 获取实体 GetInfoById
        ///	<summary>
        ///	获取实体
        ///	</summary>
        ///	<param name="contentUpFileId"></param>
        ///	<returns>ContentUpFileInfo</returns>
        public ContentUpFileInfo GetInfoById(int id)
        {
            return Idal.GetInfoById(id);
        }
        #endregion

        #region 删除 DeleteInfoById
        ///	<summary>
        ///	删除(同时删除文件)
        ///	</summary>
        ///	<param name="id"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult DeleteInfoById(int id)
        {

            ContentUpFileInfo info = GetInfoById(id);
            if (info != null)
            {
                TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
            }
            return Idal.DeleteInfoByIds(id.ToString());
        }
        #endregion

        #region 删除 DeleteInfoByIds
        ///	<summary>
        ///	删除
        ///	</summary>
        ///	<param name="ids"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult DeleteInfoByIds(string ids)
        {
            return Idal.DeleteInfoByIds(ids);
        }
        #endregion

        #region 自定义列表（无分页） GetListByCondition
        ///	<summary>
        ///	自定义列表（无分页）
        ///	</summary>
        ///	<param name="topn">前N条，为0时表示所有符合条件的</param>
        ///	<param name="condition">自定义条件，要以And开头</param>
        ///	<param name="orderby">排序，不需要Order by </param>
        ///	<returns>List<ContentUpFileInfo></returns>
        public List<ContentUpFileInfo> GetListByCondition(int topn, string condition, string orderby)
        {
            return Idal.GetListByCondition(topn, condition, orderby);
        }
        /// <summary>
        /// 获取datatable
        /// </summary>
        /// <param name="topn"></param>
        /// <param name="strColumns"></param>
        /// <param name="condition"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public DataTable GetDtListByCondition(int topn, string strColumns, string condition, string orderby)
        {
            return Idal.GetDtListByCondition(topn, strColumns, condition, orderby);
        }
        #endregion

        #region 自定义列表（分页） GetListByPager
        ///	<summary>
        ///	自定义列表（分页）
        ///	</summary>
        ///	<returns>List<ContentUpFileInfo></returns>
        public List<ContentUpFileInfo> GetListByPager(int pageNumber, int pageSize, string condition, string orderby, out int recordCount)
        {
            return Idal.GetListByPager(pageNumber, pageSize, condition, orderby, out  recordCount);
        }
        #endregion


        #region 通过路径获取实体
        /// <summary>
        /// 通过路径获取实体
        /// </summary>
        /// <param name="FileRoot">路径</param>
        /// <returns></returns>
        public ContentUpFileInfo GetInfoByFileRoot(string FileRoot)
        {
            return Idal.GetInfoByFileRoot(FileRoot);
        }
        #endregion



        #region 通过ContentId删除附件
        /// <summary>
        /// 通过ContentId删除附件
        /// </summary>
        /// <param name="ContentId"></param>
        /// <returns></returns>
        public EnumSubmitResult DeleteInfoByContentId(int ContentId)
        {
            EnumSubmitResult enumResult = EnumSubmitResult.Success;
            string strCondition = "", strOrderBy = "";
            strCondition = " AND ContentId=" + ContentId;
            strOrderBy = " ContentUpFileId DESC";
            List<ContentUpFileInfo> m_ContentUpFileInfoList = GetListByCondition(0, strCondition, strOrderBy);
            foreach (ContentUpFileInfo info in m_ContentUpFileInfoList)
            {
                TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
            }
            enumResult = Idal.DeleteInfoByContentIds(ContentId.ToString());
            return enumResult;
        }


        /// <summary>
        /// 通过ContentId删除附件
        /// </summary>
        /// <param name="ContentIds"></param>
        /// <returns></returns>
        public EnumSubmitResult DeleteInfoByContentId(string ContentIds)
        {
            EnumSubmitResult enumResult = EnumSubmitResult.Success;
            string strCondition = "", strOrderBy = "";
            strCondition = " AND ContentId in(" + ContentIds + ")";
            strOrderBy = " ContentUpFileId DESC";
            List<ContentUpFileInfo> m_ContentUpFileInfoList = GetListByCondition(0, strCondition, strOrderBy);
            foreach (ContentUpFileInfo info in m_ContentUpFileInfoList)
            {
                TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
            }
            enumResult = Idal.DeleteInfoByContentIds(ContentIds);
            return enumResult;
        }

        /// <summary>
        /// 通过ContentId删除附件
        /// </summary>
        /// <param name="ContentIds"></param>
        /// <param name="delAttr">删除附件</param>
        /// <param name="delImg">删除图片</param>
        /// <returns></returns>
        public EnumSubmitResult DeleteInfoByContentId(string ContentIds, bool delAttr, bool delImg)
        {
            EnumSubmitResult enumResult = EnumSubmitResult.Success;
            string strCondition = "", strOrderBy = "";
            strCondition = " AND ContentId in(" + ContentIds + ")";
            strOrderBy = " ContentUpFileId DESC";
            List<ContentUpFileInfo> m_ContentUpFileInfoList = GetListByCondition(0, strCondition, strOrderBy);
            foreach (ContentUpFileInfo info in m_ContentUpFileInfoList)
            {
                if (delAttr)
                {
                    if (info.AttributeID == (int)AttributeType.EnumElement.Attr)
                    {
                        TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
                        enumResult = Idal.DeleteInfoByContentIds(info.ContentId.ToString());
                    }
                }

                if (delImg)
                {
                    if (info.AttributeID == (int)AttributeType.EnumElement.Pic)
                    {
                        TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
                        enumResult = Idal.DeleteInfoByContentIds(info.ContentId.ToString());
                    }
                }

            }

            return enumResult;
        }
        #endregion

        #region 通过结点ID删除附件
        /// <summary>
        /// 通过结点ID删除附件
        /// </summary>
        /// <param name="NodeId"></param>
        /// <returns></returns>
        public EnumSubmitResult DeleteInfoByNodeId(int NodeId)
        {
            string strCondition = "", strOrderBy = "";
            strCondition = " AND NodeId =" + NodeId;
            strOrderBy = " ContentUpFileId DESC";
            List<ContentUpFileInfo> m_ContentUpFileInfoList = GetListByCondition(0, strCondition, strOrderBy);
            foreach (ContentUpFileInfo info in m_ContentUpFileInfoList)
            {
                TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
            }

            return Idal.DeleteInfoByNodeId(NodeId);
        }

        /// <summary>
        /// 通过结点ID删除附件
        /// </summary>
        /// <param name="NodeId"></param>
        /// <param name="delAttr">附件类型</param>
        /// <param name="delImg">图片类型</param>
        /// <returns></returns>
        public EnumSubmitResult DeleteInfoByNodeId(int NodeId, bool delAttr, bool delImg)
        {
            string strCondition = "", strOrderBy = "";
            strCondition = " AND NodeId =" + NodeId;
            strOrderBy = " ContentUpFileId DESC";
            List<ContentUpFileInfo> m_ContentUpFileInfoList = GetListByCondition(0, strCondition, strOrderBy);
            foreach (ContentUpFileInfo info in m_ContentUpFileInfoList)
            {
                if (delAttr)
                {
                    if (info.AttributeID == (int)AttributeType.EnumElement.Attr)
                    {
                        TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
                    }
                }

                if (delImg)
                {
                    if (info.AttributeID == (int)AttributeType.EnumElement.Pic)
                    {
                        TRPOP.Common.FileUtil.DeleteFile(info.FileRoot, false, "");
                    }
                }
            }

            return Idal.DeleteInfoByNodeId(NodeId);
        }
        #endregion


        #region 保存编辑器的上传文件
        /// <summary>
        /// 保存编辑器的上传文件
        /// </summary>
        /// <param name="strKey">session名字</param>
        /// <param name="intNodeId"></param>
        /// <param name="intContentId"></param>
        /// <param name="AdminId"></param>
        public void SaveEditorUpLoadFile(string strKey, int intNodeId, int intContentId, int AdminId)
        {
            string value = "";
            string basePath = Common.Util.GetMapPath("/");
            if (strKey != "")
            {
                if (HttpContext.Current.Session[strKey] != null)
                {
                    value = HttpContext.Current.Session[strKey].ToString();
                    if (value != "")
                    {
                        //value = value.Replace(basePath,"");
                        string[] filepath = value.Split('|');
                        for (int i = 0; i < filepath.Length; i++)
                        {

                            ContentUpFileInfo info = new ContentUpFileInfo();
                            string fullPath = filepath[i];
                            if (System.IO.File.Exists(fullPath))
                            {
                                #region 信息保存
                                FileInfo f = new FileInfo(fullPath);
                                info.FileSize = f.Length / 1024;

                                string path = "";
                                path = fullPath.Replace(basePath, "");
                                path = path.Replace("\\", "/");
                                info.FileRoot = "/" + path;
                                string ext = "";
                                if (path.IndexOf(".") > 0)
                                {
                                    ext = path.Substring(path.LastIndexOf(".") + 1).ToLower();
                                }

                                if (SYSConfig.AttachmentSetting.UpImageType.IndexOf(ext) >= 0)
                                {
                                    info.AttributeID = (int)AttributeType.EnumElement.Pic;
                                }
                                else
                                {
                                    info.AttributeID = (int)AttributeType.EnumElement.Attr;
                                }
                                info.ContentId = intContentId;
                                info.NodeID = intNodeId;
                                info.Category = ext;
                                info.AddTime = DateTime.Now;
                                info.AddUserId = AdminId;
                                Save(info);
                                #endregion
                            }


                        }
                    }

                    HttpContext.Current.Session[strKey] = null;
                }
            }
        }
        /// <summary>
        /// 保存编辑器的上传文件
        /// </summary>
        /// <param name="strKey"></param>
        /// <param name="node"></param>
        /// <param name="intContentId"></param>
        /// <param name="AdminId"></param>
        public void SaveEditorUpLoadFile(string strKey, NodeInfo node, int intContentId, int AdminId)
        {
            string value = "";
            int intNodeId = node.NodeId;
            string basePath = Common.Util.GetMapPath("/");
            if (strKey != "")
            {
                if (HttpContext.Current.Session[strKey] != null)
                {
                    value = HttpContext.Current.Session[strKey].ToString();
                    if (value != "")
                    {
                        //value = value.Replace(basePath,"");
                        string[] filepath = value.Split('|');

                        for (int i = 0; i < filepath.Length; i++)
                        {

                            ContentUpFileInfo info = new ContentUpFileInfo();
                            string fullPath = Common.Util.GetMapPath(filepath[i]);
                            if (System.IO.File.Exists(fullPath))
                            {
                                #region 信息保存
                                FileInfo f = new FileInfo(fullPath);
                                info.FileSize = f.Length / 1024;

                                string path = filepath[i];
                                
                                info.FileRoot =  path;
                                string ext = "";
                                if (path.IndexOf(".") > 0)
                                {
                                    ext = path.Substring(path.LastIndexOf(".") + 1).ToLower();
                                }

                                if (SYSConfig.AttachmentSetting.UpImageType.IndexOf(ext) >= 0)
                                {
                                    info.AttributeID = (int)AttributeType.EnumElement.Pic;
                                }
                                else
                                {
                                    info.AttributeID = (int)AttributeType.EnumElement.Attr;
                                }
                                info.ContentId = intContentId;
                                info.NodeID = intNodeId;
                                info.Category = ext;
                                info.AddTime = DateTime.Now;
                                info.AddUserId = AdminId;
                                Save(info);
                                #endregion
                            }


                        }
                    }

                    HttpContext.Current.Session[strKey] = null;
                }
            }
        }

        /// <summary>
        ///  保存编辑器的上传文件
        /// </summary>
        /// <param name="strKey"></param>
        /// <param name="intNodeId"></param>
        /// <param name="intContentId"></param>
        /// <param name="AdminId"></param>
        /// <param name="Type">附件属性</param>
        public void SaveEditorUpLoadFile(string strKey, int intNodeId, int intContentId, int AdminId, AttributeType.EnumElement Type)
        {
            string value = "";
            string basePath = Common.Util.GetMapPath("/");
            if (strKey != "")
            {
                if (HttpContext.Current.Session[strKey] != null)
                {
                    value = HttpContext.Current.Session[strKey].ToString();
                    if (value != "")
                    {
                        //value = value.Replace(basePath,"");
                        string[] filepath = value.Split('|');
                        for (int i = 0; i < filepath.Length; i++)
                        {

                            ContentUpFileInfo info = new ContentUpFileInfo();
                            string fullPath = filepath[i];
                            if (System.IO.File.Exists(fullPath))
                            {
                                #region 信息保存
                                FileInfo f = new FileInfo(fullPath);
                                info.FileSize = f.Length / 1024;

                                string path = "";
                                path = fullPath.Replace(basePath, "");
                                path = path.Replace("\\", "/");
                                info.FileRoot = "/" + path;
                                string ext = "";
                                if (path.IndexOf(".") > 0)
                                {
                                    ext = path.Substring(path.LastIndexOf(".") + 1).ToLower();
                                }

                                info.AttributeID = (int)Type;
                                info.ContentId = intContentId;
                                info.NodeID = intNodeId;
                                info.Category = ext;
                                info.AddTime = DateTime.Now;
                                info.AddUserId = AdminId;
                                Save(info);
                                #endregion
                            }


                        }
                    }

                    HttpContext.Current.Session[strKey] = null;
                }
            }
        }


       /// <summary>
        /// 保存编辑器的上传文件
       /// </summary>
       /// <param name="strKey"></param>
       /// <param name="AdminId"></param>
        /// <param name="Type">附件属性</param>
        public void SaveEditorUpLoadFile(string strKey, int AdminId, AttributeType.EnumElement Type)
        {
            string value = "";
            string basePath = Common.Util.GetMapPath("/");
            if (strKey != "")
            {
                if (HttpContext.Current.Session[strKey] != null)
                {
                    value = HttpContext.Current.Session[strKey].ToString();
                    if (value != "")
                    {
                        //value = value.Replace(basePath,"");
                        string[] filepath = value.Split('|');
                        for (int i = 0; i < filepath.Length; i++)
                        {

                            ContentUpFileInfo info = new ContentUpFileInfo();
                            string fullPath = filepath[i];
                            if (System.IO.File.Exists(fullPath))
                            {
                                #region 信息保存
                                FileInfo f = new FileInfo(fullPath);
                                info.FileSize = f.Length / 1024;

                                string path = "";
                                path = fullPath.Replace(basePath, "");
                                path = path.Replace("\\", "/");
                                info.FileRoot = "/" + path;
                                string ext = "";
                                if (path.IndexOf(".") > 0)
                                {
                                    ext = path.Substring(path.LastIndexOf(".") + 1).ToLower();
                                }

                                info.AttributeID = (int)Type;
                                info.Category = ext;
                                info.AddTime = DateTime.Now;
                                info.AddUserId = AdminId;
                                Save(info);
                                #endregion
                            }


                        }
                    }

                    HttpContext.Current.Session[strKey] = null;
                }
            }
        }

        #endregion

        /// <summary>
        /// 更新某个结点下所有的fileurl
        /// </summary>
        /// <param name="intNodeID"></param>
        /// <param name="strRoot"></param>
        /// <param name="strUrlReplace"></param>
        /// <returns></returns>
        public EnumSubmitResult UpdateFileURL(int intNodeID, string strRoot, string strUrlReplace)
        {
            return Idal.UpdateFileURL(intNodeID, strRoot, strUrlReplace);
        }

    }
}
